package org.autumn.lock;

import java.util.Scanner;
import java.util.UUID;
import java.util.concurrent.ArrayBlockingQueue;

/**
 * Producer and Consumer
 */
public class TestPc {
    private static int id = 1;

    public static void main(String[] args) {
        MessageQueue queue = new MessageQueue(10);
        Scanner scanner = new Scanner(System.in);
        while (true) {
            int command = scanner.nextInt();

            if (command == 1) {
                for (int j = 0; j < 10; j++) {
                    new Thread(() -> {
                        try {
                            Message message = new Message(getId(), UUID.randomUUID().toString());
                            queue.put(message);
                            System.out.println(Thread.currentThread().getName() + " put message -> " + message);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }, "producer" + j).start();
                }
            }
            if (command == 2) {
                new Thread(() -> {
                    try {
                        System.out.println("consumer get message-> " + queue.poll());
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                }, "consumer").start();
            }
        }
    }

    public static int getId() {
        return id++;
    }
}

/**
 * 存储容器
 */
class MessageQueue {
    // 队列容器
    private ArrayBlockingQueue<Object> queue;
    // 队列大小
    private int capacity;

    public MessageQueue(int capacity) {
        queue = new ArrayBlockingQueue(capacity);
        this.capacity = capacity;
    }

    public void put(Object message) throws InterruptedException {
        synchronized (this) {
            while (queue.size() == capacity) {
                System.out.println("the queue is full ... wait consumer!");
                this.wait();
            }
            queue.put(message);
            this.notifyAll();
        }
    }

    public Object poll() throws InterruptedException {
        synchronized (this) {
            while (queue.size() == 0) {
                System.out.println("the queue is empty ... wait producer!");
                this.wait();
            }
            Object poll = queue.poll();
            this.notifyAll();
            return poll;
        }
    }

}


/**
 * 消息
 */
class Message {
    Integer id;
    String message;

    public Message(Integer id, String message) {
        this.id = id;
        this.message = message;
    }

    @Override
    public String toString() {
        return "Message{" +
                "id=" + id +
                ", message='" + message + '\'' +
                '}';
    }
}
